import React from 'react';
import { AutoComplete, Card, Upload, Divider, Image } from 'antd';
import { Form, Input, Button, Checkbox, Select, message } from 'antd';
import axios from 'axios';
import { Url } from '../url';
import { UploadOutlined } from '@ant-design/icons';
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import { DatePicker, TimePicker } from 'antd';

const { RangePicker } = DatePicker;

const { Option } = Select;
const formItemLayout = {
    labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
    },
    wrapperCol: {
        xs: { span: 14 },
        sm: { span: 14 },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 14,
            offset: 1,
        },
        sm: {
            span: 14,
            offset: 1,
        },
    },
};



export class AskPublish extends React.Component {

    state = {
        coverUrl: undefined,
        coverId: undefined,
        downloadFileUrl: undefined,
        fileId: undefined
    }

    uploadProps = {
        name: 'file',
        action: Url.uploadImage,
        onChange: (info) => {
            if (info.file.status !== 'uploading') {
                this.setState({
                    coverUrl: Url.viewImage + info.file.response,
                    coverId: info.file.response
                });
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };

    uploadFileProps = {
        name: 'file',
        action: Url.uploadFile,
        onChange: (info) => {
            if (info.file.status !== 'uploading') {
                this.setState({
                    downloadFileUrl: Url.downloadFile + "/" + info.file.response,
                    fileId: info.file.response
                });
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        showUploadList: {
            showDownloadIcon: false,
            showRemoveIcon: false,
        },
    };


    onFinish = (values) => {

        if (this.state.coverId == undefined) {
            message.error("You have to upload one cover image of this publishion.")
        } else if (this.state.fileId == undefined) {
            message.error("You have to upload one docunment.")
        } else {

            delete values.agreement;
            const htmlContent = this.state.editorState.toHTML()
            values["detail"] = htmlContent;
            values["cover"] = this.state.coverId;
            values["file"] = this.state.fileId;
            const rangeTimeValue = values['range-time-picker'];
            values["startTime"] = rangeTimeValue[0].toDate().getTime();
            values["endTime"] = rangeTimeValue[1].toDate().getTime();

            //post the information to backend
            axios.post(Url.publishAsk, values)
                .then((response) => {

                    message.success('publish succeed');
                    //delay 500ms jump to login page after registering succeed
                    setTimeout(() => {
                        window.location.href = "/#/ask/" + response.data.askId;
                    }, 500);
                })
                .catch((error) => {
                    message.error("Publish Error");
                    console.log(error);
                });
        }
    };

    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    }

    state = {
        editorState: null,
    }

    handleEditorChange = (editorState) => {
        this.setState({ editorState })
    }


    render = () => {
        const { editorState } = this.state
        const rangeConfig = {
            rules: [{ type: 'array', required: true, message: 'Please select time!' }],
        };

        let preview = <></>
        if (this.state.downloadFileUrl) {
            preview = <a href={this.state.downloadFileUrl}>Preview</a>
        }
        return (

            <div style={{ marginLeft: "10%" }}>
                <Card title="Please input your ask information" style={{ width: 900, marginTop: 15 }}>

                    <Divider orientation="left">Cover</Divider>
                    <Upload {...this.uploadProps}>
                        <Button icon={<UploadOutlined />}>Click to Upload</Button>
                    </Upload>
                    <Image
                        width={480}
                        src={this.state.coverUrl}
                        preview={{
                            src: this.state.coverUrl,
                        }}
                    />

                    <Divider style={{ marginTop: "32px" }} orientation="left">Docunment</Divider>

                    <Upload {...this.uploadFileProps}>
                        <Button icon={<UploadOutlined />}>Click to Upload</Button>
                    </Upload>

                    {preview}

                    <Divider style={{ marginTop: "32px" }} orientation="left">Basic Info</Divider>

                    <Form
                        {...formItemLayout}
                        name="basic"
                        // labelCol={{ span: 8 }}
                        // wrapperCol={{ span: 16 }}
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                    >
                        <Form.Item
                            label="AskName"
                            name="name"

                            rules={[{ required: true, message: 'Please input your AskName!' }]}
                        >
                            <Input placeholder="Please input your ask name" />
                        </Form.Item>

                        <Form.Item
                            label="Description"
                            name="description"
                            rules={[{ required: true, message: 'Please input your description!' }]}
                        >
                            <Input.TextArea placeholder="Please input your description" />
                        </Form.Item>

                        <Form.Item
                            label="Cost"
                            name="cost"
                            rules={[{ required: true, message: 'Please input your cost!' }]}
                        >
                            <Input placeholder="Please input your cost" />
                        </Form.Item>

                        <Form.Item name="range-time-picker" label="Bidding Time Range" {...rangeConfig}>
                            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                        </Form.Item>

                        <Form.Item
                            label="Category"
                            name="category"
                            rules={[{ required: true, message: 'Please input your category!' }]}
                        >
                            <Input placeholder="Please input your category" />
                        </Form.Item>

                        <Form.Item
                            label="Phone"
                            name="phone"
                            rules={[{ required: true, message: 'Please input your phone number!' }]}
                        >
                            <Input style={{ width: '100%' }} />
                        </Form.Item>

                        <Form.Item
                            label="Company"
                            name="company"
                            rules={[{ required: true, message: 'Please input your Company!' }]}
                        >
                            <Input placeholder="Please input your Company" />
                        </Form.Item>

                        <Divider orientation="left">Detail</Divider>
                        <BraftEditor
                            value={editorState}
                            onChange={this.handleEditorChange}
                            language="en"
                            style={{ border: "2px solid #ddd", borderRadius: 10 }}
                        />

                        <Divider orientation="left">Publish</Divider>
                        <Form.Item
                            name="agreement"
                            valuePropName="checked"
                            rules={[
                                {
                                    validator: (_, value) =>
                                        value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
                                },
                            ]}
                            {...tailFormItemLayout}
                        >
                            <Checkbox>
                                I have read the <a href="" target="_blank">agreement</a>
                            </Checkbox>
                        </Form.Item>
                        <Form.Item {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit">
                                Publish
                            </Button>
                        </Form.Item>

                    </Form>
                </Card>
            </div>

        )
    }
}